<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/home/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-form :inline="true" class="searchForm">
      <el-form-item>
        <el-input v-model="keyword" clearable placeholder="请输入要搜索的关键字" @clear="clear"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="add" plain icon="el-icon-plus">添加</el-button>
      </el-form-item>

      <el-form-item>
        <el-select placeholder="选择年级" clearable filterable v-model="gradeId" @change="selectChange">
          <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-cascader :options="majorList" clearable filterable :show-all-levels="false" :props="{
            expandTrigger: 'hover',
            emitPath: false,
            checkStrictly: true
          }" @change="cascaderChange">
        </el-cascader>
      </el-form-item>

      <el-form-item>
        <el-button type="danger" @click="dels" plain icon="el-icon-close" v-show="select.length != 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <!-- 表单 -->

    <el-table :data="dataList" border stripe @selection-change="selectionChange" v-loading="loading" height="550px">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="姓名" prop="realName" min-width="80px" align="center"></el-table-column>
      <el-table-column label="性别" min-width="50px" align="center">
        <template slot-scope="scope">
          {{ scope.row.sex == 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column label="qq账号" prop="qq" min-width="100px" align="center"></el-table-column>
      <el-table-column label="分队" prop="unit.unitName" min-width="100px" align="center"></el-table-column>
      <el-table-column label="班级" prop="classes.className" min-width="100px" align="center"></el-table-column>
      <el-table-column label="职务" min-width="100px" align="center">
        <template slot-scope="scope">
          <el-popover placement="top" trigger="hover">
            <el-tag type="success" size="normal" effect="plain">{{scope.row.unit?scope.row.unit.unitName:''}}</el-tag>
            <span slot="reference" class="roleName">{{scope.row.role?scope.row.role.roleName:''}}</span>
          </el-popover>

        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="detail(scope.row)" icon="el-icon-s-tools">详情</el-button>
          <el-button size="mini" type="primary" @click="edit(scope.row)" icon="el-icon-s-tools">编辑</el-button>
          <el-button size="mini" type="danger" @click="remove(scope.row)" icon="el-icon-close">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination :current-page="page.page" :total="page.total" background layout="prev, pager, next" @current-change="currentChange">
    </el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑" :visible.sync="dialogEdit" center v-loading="loading">
      <el-form class="form" :model="form" label-left label-width="100px" :rules="rules" ref="editForm">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model.number="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model.trim="form.realName"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickName">
          <el-input v-model.trim="form.nickName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio v-model="form.sex" label="1">男</el-radio>
          <el-radio v-model="form.sex" label="2">女</el-radio>
        </el-form-item>

        <el-form-item label="学号" prop="unique">
          <el-input v-model.number="form.unique"></el-input>
        </el-form-item>

        <el-form-item label="qq号码" prop="qq">
          <el-input v-model.number="form.qq"></el-input>
        </el-form-item>

        <el-form-item label="班级" prop="classId">
          <el-cascader :options="classList" v-model="form.classId" filterable :show-all-levels="false" :props="{ expandTrigger: 'hover', emitPath: false }">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doEdit('editForm')">确 定</el-button>
        <el-button @click="dialogEdit = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="新增" :visible.sync="dialogAdd" center v-loading="loading">
      <el-form class="form" :model="form" label-left label-width="100px" :rules="rules" ref="addForm">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model.number="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model.trim="form.realName"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickName">
          <el-input v-model.trim="form.nickName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio v-model="form.sex" label="1">男</el-radio>
          <el-radio v-model="form.sex" label="2">女</el-radio>
        </el-form-item>

        <el-form-item label="学号" prop="unique">
          <el-input v-model.number="form.unique"></el-input>
        </el-form-item>

        <el-form-item label="qq号码" prop="qq">
          <el-input v-model.number="form.qq"></el-input>
        </el-form-item>

        <el-form-item label="分队" prop="unitId">
          <el-select placeholder="选择分队" filterable v-model="form.unitId">
            <el-option v-for="item in unitList" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="classId">
          <el-cascader :options="classList" v-model="form.classId" filterable :show-all-levels="false" :props="{ expandTrigger: 'hover', emitPath: false }">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAdd('addForm')">确 定</el-button>
        <el-button @click="dialogAdd = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  adminUserPageApi as getPageApi,
  adminEditUserApi as editApi,
  adminAddUserApi as addApi,
  adminDelUserApi as delApi,
  adminDelsUserApi as delsApi,
  adminGetMajorListApi as getMajorList,
  adminGetGradeListApi as getGradeList,
  adminGetClassListApi as getClassList,
  adminGetUnitListApi as getUnitList,
} from "@/api/admin.js";
export default {
  inject: ["reload"],
  data() {
    return {
      //表格展示数据
      dataList: [],
      //分页数据
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      //选择的数据
      select: [],
      //加载
      loading: false,
      //表单数据
      form: {}, //表单数据
      keyword: "", //关键字
      dialogEdit: false, //显示编辑对话款
      dialogAdd: false, //显示编辑对话款
      //表单校验
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: "blur",
          },
        ],
        realName: {
          required: true,
          message: "请输入真实姓名",
          trigger: "blur",
        },
        nickName: {
          required: true,
          message: "请输入昵称",
          trigger: "blur",
        },
        sex: {
          required: true,
          message: "请选择性别",
          trigger: "blur",
        },
        unique: [
          {
            required: true,
            message: "请输入学号",
            trigger: "blur",
          },
        ],
        qq: [
          {
            required: true,
            message: "请输入qq号码",
            trigger: "blur",
          },
        ],
        gradeId: {
          required: true,
          message: "请选择年级",
          trigger: ["blur", "change"],
        },
        classId: {
          required: true,
          message: "请选择班级",
          trigger: ["blur", "change"],
        },
        unitId: {
          required: true,
          message: "请选择分队",
          trigger: ["blur", "change"],
        },
      },
      majorList: [],
      gradeList: [],
      classList: [],
      unitList: [],
      majorId: null,
      gradeId: null,
      deptId: null,
      unitId: null,
    };
  },
  methods: {
    //获取数据列表
    getList(
      page = this.page.page,
      limit = this.page.limit,
      keyword = this.keyword,
      gradeId = this.gradeId,
      majorId = this.majorId,
      deptId = this.deptId
    ) {
      let queryParam = {
        page,
        limit,
        keyword,
        gradeId,
        majorId,
        deptId,
      };
      getPageApi(queryParam)
        .then((res) => {
          this.loading = true;
          const result = res.data;
          if (result.status === 200) {
            this.dataList = result.data.content;
            this.page.total = result.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //选择
    selectionChange(e) {
      this.select = e;
    },
    //分页
    currentChange(e) {
      this.page.page = e;
      this.getList();
    },
    //打开编辑对话款
    edit(e) {
      this.form = e;
      this.form.sex = this.form.sex + "";
      this.dialogEdit = true;
    },
    //执行编辑操作
    doEdit(e) {
      this.$refs[e].validate((valid) => {
        if (valid) {
          editApi(this.form)
            .then((res) => {
              this.loading = true;
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("修改成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.loading = false;
              this.dialogEdit = false;
              this.reload();
            });
        }
      });
    },
    //打开添加对话款
    add() {
      this.form = {};
      this.form.status = true;
      this.dialogAdd = true;
    },
    //执行添加操作
    doAdd(e) {
      this.$refs[e].validate((valid) => {
        if (valid) {
          this.form.status = this.form.status ? 1 : 0;
          addApi(this.form)
            .then((res) => {
              this.loading = true;
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("添加成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.loading = false;
              this.dialogAdd = false;
              this.reload();
            });
        }
      });
    },
    //删除
    remove(e) {
      this.$confirm("确认要删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          delApi({ id: e.id })
            .then((res) => {
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.reload();
            });
        })
        .catch(() => {
          return;
        });
    },
    //批量删除
    dels() {
      const ids = this.select.map((role) => {
        return role.id;
      });
      const data = { ids };
      this.$confirm("确认要删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          delsApi(data)
            .then((res) => {
              const result = res.data;
              if (result.status == 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(result.msg);
              }
            })
            .finally(() => {
              this.reload();
            });
        })
        .catch(() => {
          return;
        });
    },
    //搜索
    search() {
      this.getList();
    },
    //清空文本框
    clear() {
      this.getList();
    },
    //获取专业列表
    getMajorList() {
      getMajorList().then((res) => {
        const result = res.data;
        if (result.status == 200) {
          const majorList = result.data;
          majorList.forEach((dept) => {
            this.majorList.push({
              label: dept.deptName,
              value: "dept-" + dept.id,
              children: dept.majorList.map((major) => {
                return {
                  label: major.majorName,
                  value: major.id,
                };
              }),
            });
          });
        }
      });
    },
    //获取年级列表
    getGradeList() {
      getGradeList().then((res) => {
        const result = res.data;
        if (result.status == 200) {
          this.gradeList = result.data;
        }
      });
    },
    //获取班级列表
    getClassList() {
      getClassList().then((res) => {
        const result = res.data;
        if (result.status == 200) {
          const classList = result.data;
          classList.forEach((dept) => {
            this.classList.push({
              label: dept.deptName,
              value: "dept-" + dept.id,
              children: dept.majorList.map((major) => {
                return {
                  label: major.majorName,
                  value: "major-" + major.id,
                  children: major.classList.map((classes) => {
                    return {
                      label: classes.className,
                      value: classes.id,
                    };
                  }),
                };
              }),
            });
          });
        }
      });
    },
    //获取分队列表
    getUnitList() {
      getUnitList().then((res) => {
        const result = res.data;
        this.unitList = result.data;
      });
    },

    //点击选择筛选条件——年级
    selectChange(e) {
      this.gradeId = e;
      this.getList();
    },
    //点击选择筛选条件——专业
    cascaderChange(e) {
      e = e + "";
      this.deptId = null;
      this.majorId = null;
      if (e.indexOf("dept-") != -1) {
        this.deptId = e.substr(5);
        this.getList();
      } else if (e.indexOf("dept-") == -1) {
        this.majorId = e;
        if (e == "null") {
          this.majorId = null;
        }
        this.getList();
      } else {
        this.getList();
      }
    },
    detail(e) {
      this.$router.push("/admin/home/user/detail/" + e.id);
    },
  },
  created() {
    this.getList();
    this.getMajorList();
    this.getGradeList();
    this.getClassList();
    this.getUnitList();
  },
};
</script>

<style scoped>
.el-tabs {
  margin-top: 50px;
}
.el-pagination {
  float: right;
  margin: 20px;
}
.searchForm {
  margin-left: 100px;
  margin-top: 20px;
}
.form {
  padding: 20px 50px;
}
.form .el-form-item {
  width: 300px;
  margin: 20px auto;
}
.roleName:hover {
  cursor: pointer;
}
</style>
